package cn.itcast.bos.controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.util.PinYin4jUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import static org.hibernate.id.enhanced.OptimizerFactory.NONE;

/**
 * Created by Administrator on 2018/12/25.
 */
@RestController
@RequestMapping("/area")
public class AreaController {

    // 注入业务层对象
    @Autowired
    private AreaService areaService;

    // 批量区域数据导入
    @RequestMapping("batchImport")
    public void batchImport(MultipartFile file) throws IOException {
        List<Area> areas = new ArrayList<Area>();
        // 编写解析代码逻辑
        // 基于.xls 格式解析 HSSF
        // 1、 加载Excel文件对象
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(file.getInputStream());
        // 2、 读取一个sheet
        HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
        // 3、 读取sheet中每一行
        for (Row row : sheet) {
            // 一行数据 对应 一个区域对象
            if (row.getRowNum() == 0) {
                // 第一行 跳过
                continue;
            }
            // 跳过空行
            if (row.getCell(0) == null
                    || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                continue;
            }
            Area area = new Area();
            area.setId(row.getCell(0).getStringCellValue());
            area.setProvince(row.getCell(1).getStringCellValue());
            area.setCity(row.getCell(2).getStringCellValue());
            area.setDistrict(row.getCell(3).getStringCellValue());
            area.setPostcode(row.getCell(4).getStringCellValue());
            // 基于pinyin4j生成城市编码和简码
            String province = area.getProvince();
            String city = area.getCity();
            String district = area.getDistrict();
            province = province.substring(0, province.length() - 1);
            city = city.substring(0, city.length() - 1);
            district = district.substring(0, district.length() - 1);
            // 简码
            String[] headArray = PinYin4jUtils.getHeadByString(province + city
                    + district);
            StringBuffer buffer = new StringBuffer();
            for (String headStr : headArray) {
                buffer.append(headStr);
            }
            String shortcode = buffer.toString();
            area.setShortcode(shortcode);
            // 城市编码
            String citycode = PinYin4jUtils.hanziToPinyin(city, "");
            area.setCitycode(citycode);

            areas.add(area);
        }
        // 调用业务层
        areaService.saveBatch(areas);

    }

    // 分页查询
    @RequestMapping("pageQuery")
    public Map<String, Object> pageQuery(int page,int rows,Area area) {
        // 构造分页查询对象
        Pageable pageable = PageRequest.of(page-1,rows);
        // 构造条件查询对象
        Specification<Area> specification = new Specification<Area>() {
            @Override
            public Predicate toPredicate(Root<Area> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(area.getProvince())) {
                    Predicate p1 = cb.like(root.get("province")
                            .as(String.class), "%" + area.getProvince() + "%");
                    list.add(p1);
                }
                if (StringUtils.isNotBlank(area.getCity())) {
                    Predicate p2 = cb.like(root.get("city").as(String.class),
                            "%" + area.getCity() + "%");
                    list.add(p2);
                }
                if (StringUtils.isNotBlank(area.getDistrict())) {
                    Predicate p3 = cb.like(root.get("district")
                            .as(String.class), "%" + area.getDistrict() + "%");
                    list.add(p3);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        // 调用业务层完成查询
        Page<Area> pageData = areaService.findPageData(specification, pageable);

        // 将返回page对象 转换datagrid需要格式
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", pageData.getTotalElements());
        result.put("rows", pageData.getContent());

        return result;
    }

}
